package com.qf.ayc.config;
//不实现不报错因为是default，里面默认实现了

;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.ayc.user.entity.Users;
import com.qf.ayc.user.mapper.UsersMapper;
import com.qf.ayc.utils.JwtUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component//Interceptor这个对象就是组件，起到框架作用
public class Interceptor implements HandlerInterceptor {
    //control+o覆盖哪个方法
    @Autowired
    private UsersMapper usersMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1，请求头的token获取
        String token = request.getHeader("token");
        String username = request.getParameter("username");

        QueryWrapper<Users> username1 = new QueryWrapper<Users>().eq("username", username);

        Users users = usersMapper.selectOne(username1);
        log.info("5254235425user{}", users);
//        //2，校验token
        if (token == null) {
            log.info("请求头中没有携带token，拦截器拦截了该请求path={}", request.getRequestURI());
//          return false;//没有token，就到此为止
            // 这里抛出异常，由Token的异常处理器进行异常捕获并返回json
//            throw new RuntimeException("请求头没有token");
            TokenException tokenException = new TokenException();
            tokenException.setCode(-3);
            tokenException.setTokenMsg("请求头里面没有token");
            throw tokenException;//填好异常对象里面的属性值，扔出去，被全局异常逮到，然后进行全局异常的代码
        }
        if (!JwtUtils.checkToken(token)) {
            log.info("token校验失败了,path={}", request.getRequestURI());
//            return false;//没有token，就到此为止
//            throw new RuntimeException("请求头token失效");
            TokenException tokenException = new TokenException();
            tokenException.setCode(-4);
            tokenException.setTokenMsg("token失效");
            throw tokenException;
        }
        //3，放行请求
        log.info("token校验通过了,请求的路径为path={}", request.getRequestURI());//只有接口路径，url是全的路径
        return true;
    }
}
